package com.winderinfo.yikaotianxia.core.http;

import android.util.Log;

import com.google.gson.Gson;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.winderinfo.yikaotianxia.core.api.Api;
import com.winderinfo.yikaotianxia.core.api.ServiceApi;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetworkRequest {
    //网络的前半段
    private final ServiceApi serviceApi;

    public NetworkRequest() {
        //日记拦截
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("message", message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);
        //okhttp
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                      /*  //获得请求头
                       SharedPreferences status = TechApp.getInstance().getSharedPreferences("status", Context.MODE_PRIVATE);
                        int userId = status.getInt("userId", 0);
                        String sessionId = status.getString("sessionId", "");
                        //判断请求头是否为空
                       if (!TextUtils.isEmpty(userId + "") && !TextUtils.isEmpty(sessionId)) {
                            //不为空统一添加
                            Request request = chain.request().newBuilder()
                                    .addHeader("userId", userId + "")
                                    .addHeader("sessionId", sessionId)
                                    .build();
                            return chain.proceed(request);
                        } else {*/
                        //为空不添加
                        Request request = chain.request();
                        return chain.proceed(request);
                        /* }*/
                    }
                }).build();
        //封装Retrofit
        Retrofit build = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .client(okHttpClient)
                .build();
        //动态代理
        serviceApi = build.create(ServiceApi.class);
    }


    public static NetworkRequest getNetworkRequest() {
        return NetWorkHolder.NETWORK_REQUEST;
    }

    //静态内部类
    public static class NetWorkHolder {
        private static final NetworkRequest NETWORK_REQUEST = new NetworkRequest();
    }

    //请求成功失败的回调
    public interface HttpListener {
        //成功的回调
        void success(String data);

        //失败的回调
        void failure(String data);
    }

    //切换
    public Observer getObserver(final HttpListener httpListener) {
        Observer<ResponseBody> observer = new io.reactivex.Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody value) {
                //请求成功结果
                if (httpListener != null) {
                    try {
                        String string = value.string();
                        httpListener.success(string);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                //失败的结果
                if (httpListener != null) {
                   //httpListener.success(e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }
        };
        return observer;
    }

    //封装get
    public NetworkRequest get(String url, Map<String, Object> map, HttpListener httpListener) {
        //判断集合为不为空
        if (map == null) {
            map = new HashMap<>();
        }
        //网络请求
        serviceApi.get(url, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(httpListener));
        return NetworkRequest.getNetworkRequest();
    }

    //封装post
    public NetworkRequest post(String url, Map<String, Object> map, HttpListener httpListener) {
        //判断集合为不为空
        if (map == null) {
            map = new HashMap<>();
        }
        //网络请求
        serviceApi.post(url, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(httpListener));
        return NetworkRequest.getNetworkRequest();
    }

    //封装put
    public NetworkRequest put(String url, Map<String, Object> map, HttpListener httpListener) {
        //判断集合为不为空
        if (map == null) {
            map = new HashMap<>();
        }
        //网络请求
        serviceApi.put(url, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(httpListener));
        return NetworkRequest.getNetworkRequest();
    }

    //封装delete
    public NetworkRequest delete(String url, Map<String, Object> map, HttpListener httpListener) {
        //判断集合为不为空
        if (map == null) {
            map = new HashMap<>();
        }
        //网络请求
        serviceApi.delete(url, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(httpListener));
        return NetworkRequest.getNetworkRequest();
    }

    //单张上传
    public void imagePost(String url, Map<String, String> map, HttpListener httpListener) {
        //判断集合为不为空
        if (map == null) {
            map = new HashMap<>();
        }
        MultipartBody multipartBody = filesMutipar(map);
        serviceApi.imagePost(url, multipartBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(httpListener));
    }

    public static MultipartBody filesMutipar(Map<String, String> map) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("image")) {
                File file = new File(entry.getValue());
                builder.addFormDataPart(entry.getKey(), "tp.png", RequestBody.create(MediaType.parse("multipart/form-data"), file));
            }
        }
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

}
